<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->

<template>
  <div class="min-h-screen bg-gray-50">
    <!-- Hero 区域 -->
    <div class="relative overflow-hidden bg-gradient-to-r from-blue-50 to-indigo-50">
      <div class="container mx-auto px-4 py-8 max-w-screen-2xl flex flex-col md:flex-row items-center">
        <div class="md:w-1/2 mb-10 md:mb-0 z-10">
          <h1 class="text-4xl md:text-5xl font-bold text-gray-800 leading-tight mb-6">
            发现和分享<span class="text-blue-600">最佳AI工具</span>
          </h1>
          <p class="text-lg text-gray-600 mb-8">
            探索由社区驱动的智能工具平台，找到提升工作效率的最佳解决方案，
            分享您的发现并获得认可。
          </p>
          <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 max-w-md">
            <a-button type="primary" size="large" class="!rounded-button whitespace-nowrap cursor-pointer w-full" @click="navigateToAIEfficiency">
              <search-outlined />
              探索工具库
            </a-button>
            <a-button size="large" class="!rounded-button whitespace-nowrap cursor-pointer w-full" @click="openPublishModal">
              <plus-outlined />
              贡献新工具
            </a-button>
          </div>
        </div>
        <div class="md:w-1/2 z-10">
          <img 
            src="../assets/9f44dd99db193094058febfea6a8e094.jpg" 
            alt="AI工具平台" 
            class="w-11/12 h-auto rounded-lg shadow-xl object-cover object-top mx-auto"
          />
        </div>
      </div>
    </div>

    <!-- 平台数据概览 -->
    <div class="container mx-auto px-6 py-8">
      <div class="text-center mb-8">
        <h2 class="text-3xl font-bold text-gray-800 mb-4">平台数据概览</h2>
        <p class="text-gray-600 max-w-2xl mx-auto">
          实时追踪平台关键指标，了解最新动态和趋势
        </p>
      </div>
      
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <div class="bg-white p-6 rounded-lg shadow-md border border-gray-100 hover:shadow-lg transition-shadow">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-gray-700">工具总数</h3>
            <app-store-outlined class="text-blue-500 text-2xl" />
          </div>
          <p class="text-3xl font-bold text-gray-800 mb-2">{{ formatNumber(totalTools) }}</p>
          <p class="text-sm text-green-600">
            <arrow-up-outlined /> 较上月增长 {{ growthRate.tools }}%
          </p>
        </div>
        
        <div class="bg-white p-6 rounded-lg shadow-md border border-gray-100 hover:shadow-lg transition-shadow">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-gray-700">累计使用次数</h3>
            <bar-chart-outlined class="text-indigo-500 text-2xl" />
          </div>
          <p class="text-3xl font-bold text-gray-800 mb-2">{{ formatNumber(totalUsage) }}</p>
          <p class="text-sm text-green-600">
            <arrow-up-outlined /> 较上月增长 {{ growthRate.usage }}%
          </p>
        </div>
        
        <div class="bg-white p-6 rounded-lg shadow-md border border-gray-100 hover:shadow-lg transition-shadow">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-gray-700">活跃用户</h3>
            <team-outlined class="text-purple-500 text-2xl" />
          </div>
          <p class="text-3xl font-bold text-gray-800 mb-2">{{ formatNumber(activeUsers) }}</p>
          <p class="text-sm text-green-600">
            <arrow-up-outlined /> 较上月增长 {{ growthRate.users }}%
          </p>
        </div>
        
        <div class="bg-white p-6 rounded-lg shadow-md border border-gray-100 hover:shadow-lg transition-shadow">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-gray-700">平均评分</h3>
            <star-outlined class="text-yellow-500 text-2xl" />
          </div>
          <p class="text-3xl font-bold text-gray-800 mb-2">{{ averageRating }}</p>
          <p class="text-sm text-green-600">
            <arrow-up-outlined /> 较上月提升 {{ growthRate.rating }}%
          </p>
        </div>
      </div>
    </div>

    <!-- 排行榜区域 -->
    <div class="container mx-auto px-6 py-12 bg-white rounded-lg shadow-sm">
      <div class="text-center mb-12">
        <h2 class="text-3xl font-bold text-gray-800 mb-4">数据排行榜</h2>
        <p class="text-gray-600 max-w-2xl mx-auto">
          探索平台上最受欢迎的工具、最活跃的贡献者以及评分最高的解决方案
        </p>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
        <!-- 常用工具排行榜 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden border border-gray-100">
          <div class="bg-gradient-to-r from-blue-500 to-blue-600 px-6 py-4">
            <div class="flex items-center justify-between">
              <h3 class="text-xl font-bold text-white">热门工具 TOP5</h3>
              <fire-outlined class="text-yellow-300 text-2xl" />
            </div>
            <p class="text-blue-100 text-sm">按使用量排序</p>
          </div>
          
          <div class="p-4">
    
            <div class="space-y-3">
              <a 
                v-for="(tool, index) in popularTools" 
                :key="tool.id"
                :href="tool.url"
                class="flex items-center p-3 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer"
                :class="{'bg-blue-50': index < 3}"
              >
                <div 
                  class="w-8 h-8 flex items-center justify-center rounded-full mr-4 text-white font-bold"
                  :class="getRankingClass(index)"
                >
                  {{ index + 1 }}
                </div>
                <div class="flex-grow">
                  <h4 class="font-medium text-gray-800">{{ tool.name }}</h4>
                  <p class="text-xs text-gray-500">{{ tool.category }}</p>
                </div>
                <div class="text-right">
                  <p class="font-semibold text-gray-800">{{ formatNumber(tool.usageCount) }}</p>
                  <p class="text-xs text-gray-500">使用次数</p>
                </div>
              </a>
            </div>
            
            <!-- <div class="mt-6 text-center">
              <a-button type="link" class="!rounded-button whitespace-nowrap cursor-pointer">
                查看更多 <right-outlined />
              </a-button>
            </div> -->
          </div>
        </div>
        
        <!-- AI工具贡献榜 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden border border-gray-100">
          <div class="bg-gradient-to-r from-purple-500 to-purple-600 px-6 py-4">
            <div class="flex items-center justify-between">
              <h3 class="text-xl font-bold text-white">AI应用贡献达人 TOP5</h3>
              <trophy-outlined class="text-yellow-300 text-2xl" />
            </div>
            <p class="text-purple-100 text-sm">按AI应用贡献工具数量排序</p>
          </div>
          <div class="p-4">
  
            <div class="space-y-3">
              <div 
                v-for="(contributor, index) in topContributors" 
                :key="contributor.id"
                class="flex items-center p-3 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer"
                :class="{'bg-purple-50': index < 3}"
              >
                <div 
                  class="w-8 h-8 flex items-center justify-center rounded-full mr-4 text-white font-bold"
                  :class="getRankingClass(index)"
                >
                  {{ index + 1 }}
                </div>
                <div class="w-10 h-10 rounded-full overflow-hidden mr-3">
                  <img :src="contributor.avatar" :alt="contributor.name" class="w-full h-full object-cover" />
                </div>
                <div class="flex-grow">
                  <h4 class="font-medium text-gray-800">{{ contributor.name }}</h4>
                  <p class="text-xs text-gray-500">{{ contributor.level }}</p>
                </div>
                <div class="text-right">
                  <p class="font-semibold text-gray-800">{{ contributor.contributionCount }}</p>
                  <p class="text-xs text-gray-500">贡献工具</p>
                </div>
              </div>
            </div>
            
            <!-- <div class="mt-6 text-center">
              <a-button type="link" class="!rounded-button whitespace-nowrap cursor-pointer">
                查看更多 <right-outlined />
              </a-button>
            </div> -->
          </div>
        </div>
        
        <!-- 工具评分排行榜 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden border border-gray-100">
          <div class="bg-gradient-to-r from-yellow-500 to-yellow-600 px-6 py-4">
            <div class="flex items-center justify-between">
              <h3 class="text-xl font-bold text-white">好评工具 TOP5</h3>
              <star-filled class="text-yellow-300 text-2xl" />
            </div>
            <p class="text-yellow-100 text-sm">按评分排序</p>
          </div>
          
          <div class="p-4">
    
            <div class="space-y-3">
              <a 
                v-for="(tool, index) in topRatedTools" 
                :key="tool.id"
                :href="tool.url"
                class="flex items-center p-3 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer"
                :class="{'bg-yellow-50': index < 3}"
              >
                <div 
                  class="w-8 h-8 flex items-center justify-center rounded-full mr-4 text-white font-bold"
                  :class="getRankingClass(index)"
                >
                  {{ index + 1 }}
                </div>

                <div class="flex-grow">
                  <h4 class="font-medium text-gray-800">{{ tool.name }}</h4>
                </div>
                <div class="text-right mr-4">
                  <div class="flex items-center justify-end mb-1">
                    <a-rate :value="tool.rating" disabled :count="5" class="text-xs" />
                  </div>
                </div>

                <div class="text-right">
                  <p class="font-semibold text-gray-800">{{ tool.rating.toFixed(1) }}</p>
                  <p class="text-xs text-gray-500">平均评分</p>
                </div>

              </a>
            </div>
            
            <!-- <div class="mt-6 text-center">
              <a-button type="link" class="!rounded-button whitespace-nowrap cursor-pointer">
                查看更多 <right-outlined />
              </a-button>
            </div> -->
          </div>
        </div>
      </div>
    </div>


    <!-- 工具类别分布 -->
    <div class="container mx-auto px-6 py-8">
      <div class="text-center mb-8">
        <h2 class="text-3xl font-bold text-gray-800 mb-4">工具类别分布</h2>
        <p class="text-gray-600 max-w-2xl mx-auto">
          了解平台上不同类别工具的分布情况，发现最受欢迎的工具类型
        </p>
      </div>
      
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <div class="bg-white p-6 rounded-lg shadow-md">
          <h3 class="text-xl font-bold text-gray-800 mb-4">工具类别占比</h3>
          <div ref="categoryChartRef" class="w-full h-80"></div>
        </div>
        
        <div class="bg-white p-6 rounded-lg shadow-md">
          <h3 class="text-xl font-bold text-gray-800 mb-4">月度工具上线趋势</h3>
          <div ref="usageTrendChartRef" class="w-full h-80"></div>
        </div>
      </div>
    </div>

    <!-- 返回顶部按钮 -->
    <div 
      v-show="showBackToTop" 
      class="fixed bottom-8 right-8 bg-blue-600 text-white p-3 rounded-full shadow-lg cursor-pointer hover:bg-blue-700 transition-colors"
      @click="scrollToTop"
    >
      <arrow-up-outlined class="text-xl" />
    </div>
  </div>

  <!-- 发布工具弹窗 -->
  <PublishTool v-model:visible="showPublishModal" />
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import { getRandomAvatar } from '@/utils/getRandomAvatar';
import PublishTool from '@/components/PublishTool.vue';
import { getIndexStats, getIndexRankings, getIndexDistribution } from '@/utils/api';
import { getTypeName } from '@/utils/constantsMapping';
import { 
  SearchOutlined, 
  PlusOutlined,
  BarChartOutlined,
  TeamOutlined,
  StarOutlined,
  FireOutlined,
  TrophyOutlined,
  StarFilled,
  RightOutlined,
  ArrowUpOutlined,
} from '@ant-design/icons-vue';

// 平台数据
const totalTools = ref(0);
const totalUsage = ref(0);
const activeUsers = ref(0);
const averageRating = ref(0);

// 获取首页统计数据
const fetchIndexStats = async () => {
  try {
    const res = await getIndexStats();
    console.log('获取首页统计数据:', res);
      totalTools.value =res.totalTools;
      totalUsage.value = res.totalUsage;
      activeUsers.value = res.activeUsers;
      averageRating.value =res.averageRating;
  
  } catch (error) {
    console.error('获取首页统计数据失败:', error);
  }
};
const growthRate = ref({
  tools: 12.5,
  usage: 18.7,
  users: 15.2,
  rating: 3.8
});

// 时间范围选择
const toolTimeRange = ref('month');
const contributorTimeRange = ref('month');
const ratingTimeRange = ref('month');

// 排行榜数据
const popularTools = ref([]);
const topContributors = ref([]);
const topRatedTools = ref([]);

// 获取排行榜数据
const fetchRankingsData = async () => {
  try {
    const res = await getIndexRankings();
    console.log('获取排行榜数据:', res);
    if (res) {
      // 热门工具数据
      popularTools.value = res.hotTools.map(tool => ({
        id: tool.toolId,
        name: tool.toolName,
        category: tool.category,
        usageCount: tool.usageCount,
        url: `#/tool/${tool.toolId}`
      }));

      // 贡献者数据
      topContributors.value = res.topContributors.map(contributor => ({
        id: contributor.userId,
        name: contributor.userName,
        level: getTypeName(contributor.groupName),
        contributionCount: contributor.aiToolCount,
        avatar: getRandomAvatar()
      }));

      // 好评工具数据
      topRatedTools.value = res.topRatedTools.map(tool => ({
        id: tool.toolId,
        name: tool.toolName,
        rating: Number(tool.rating),  // 确保rating是数值类型
        reviewCount: tool.usageCount,
        url: `#/tool/${tool.toolId}`
      }));
    }
  } catch (error) {
    console.error('获取排行榜数据失败:', error);
  }
};

// 图表引用
const categoryChartRef = ref<HTMLElement | null>(null);
const usageTrendChartRef = ref<HTMLElement | null>(null);
let categoryChart: echarts.ECharts | null = null;
let usageTrendChart: echarts.ECharts | null = null;

// 返回顶部功能
const showBackToTop = ref(false);
const showPublishModal = ref(false);
const router = useRouter();

// 导航到AI提效页面
const navigateToAIEfficiency = () => {
  router.push('/ai-efficiency/apps');
};

// 打开发布工具弹窗
const openPublishModal = () => {
  showPublishModal.value = true;
};

// 格式化数字
const formatNumber = (num: number): string => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M';
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K';
  }
  return num.toString();
};

// 获取排名样式
const getRankingClass = (index: number): string => {
  if (index === 0) return 'bg-yellow-500';
  if (index === 1) return 'bg-gray-400';
  if (index === 2) return 'bg-yellow-700';
  return 'bg-gray-500';
};

// 获取并更新图表数据
const fetchAndUpdateCharts = async () => {
  try {
    const res = await getIndexDistribution();
    console.log('获取图表数据:', res);
    if (res) {
      updateCategoryChart(res.categoryDistribution);
      updateTrendChart(res.monthlyTrend);
    }
  } catch (error) {
    console.error('获取图表数据失败:', error);
  }
};

// 更新类别分布图表
const updateCategoryChart = (data) => {
  if (categoryChartRef.value) {
    categoryChart = echarts.init(categoryChartRef.value);
    const categoryOption = {
      animation: false,
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: data.map(item => item.name)
      },
      series: [
        {
          name: '工具类别',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: data
        }
      ]
    };
    categoryChart.setOption(categoryOption);
  }
};

// 更新趋势图表
const updateTrendChart = (data) => {
  if (usageTrendChartRef.value) {
    usageTrendChart = echarts.init(usageTrendChartRef.value);
    const usageTrendOption = {
      animation: false,
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>{a}: {c} 个工具',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.map(item => item.month)
      },
      yAxis: {
        type: 'value',
        name: '工具数量',
        minInterval: 1
      },
      series: [
        {
          name: '新上线工具',
          type: 'line',
          smooth: true,
          data: data.map(item => item.count),
          itemStyle: {
            color: '#3b82f6'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(59, 130, 246, 0.5)'
                },
                {
                  offset: 1,
                  color: 'rgba(59, 130, 246, 0.05)'
                }
              ]
            }
          }
        }
      ]
    };
    usageTrendChart.setOption(usageTrendOption);
  }
};

// 初始化图表
const initCharts = () => {
  fetchAndUpdateCharts();
};

// 监听滚动事件
const handleScroll = () => {
  showBackToTop.value = window.scrollY > 300;
};

// 返回顶部
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

// 窗口大小变化时重绘图表
const handleResize = () => {
  if (categoryChart) categoryChart.resize();
  if (usageTrendChart) usageTrendChart.resize();
};

onMounted(() => {
  fetchIndexStats();
  fetchRankingsData();
  nextTick(() => {
    initCharts();
    window.addEventListener('scroll', handleScroll);
    window.addEventListener('resize', handleResize);
  });
});

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
  window.removeEventListener('resize', handleResize);
  if (categoryChart) categoryChart.dispose();
  if (usageTrendChart) usageTrendChart.dispose();
});
</script>

<style scoped>
:deep(.ant-rate-star) {
  font-size: 14px;
  margin-right: 2px;
}
</style>

